package com.ruoyi.common.utils.poi;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.List;
import java.util.Map;

public class DynamicExcelUtil {

    /**
     * 动态生成Excel
     * @param title 表头
     * @param data 数据
     * @return 字节输入流
     */
    public static ByteArrayInputStream generateExcel(List<String> title, List<Map<String, Object>> data) throws IOException {
        try (Workbook workbook = new XSSFWorkbook()) {
            Sheet sheet = workbook.createSheet("数据报表");

            // 创建表头
            Row headerRow = sheet.createRow(0);
            for (int i = 0; i < title.size(); i++) {
                Cell cell = headerRow.createCell(i);
                cell.setCellValue(title.get(i));
            }

            // 填充数据
            for (int i = 0; i < data.size(); i++) {
                Row dataRow = sheet.createRow(i + 1);
                Map<String, Object> rowData = data.get(i);
                int cellIndex = 0;
                for (Object value : rowData.values()) {
                    Cell cell = dataRow.createCell(cellIndex++);
                    if (value != null) {
                        cell.setCellValue(value.toString());
                    }
                }
            }

            // 自适应列宽
            for (int i = 0; i < title.size(); i++) {
                sheet.autoSizeColumn(i);
            }

            // 转换为字节流
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            workbook.write(out);
            return new ByteArrayInputStream(out.toByteArray());
        }
    }

}